package com.hzlj.position.locate.differentiation.sysCheck.powerOff;

import cn.hutool.core.util.ObjectUtil;
import com.hzlj.position.config.common.dto.common.LocateTimerTask;
import com.hzlj.position.config.common.dto.common.PositionAddDTO;
import com.hzlj.position.locate.common.enums.DifferentiationDataType;
import com.hzlj.position.locate.differentiation.DifferentiationService;
import com.hzlj.position.locate.differentiation.sysCheck.SysCheck;
import com.hzlj.position.locate.service.DifferentiationConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hzlj.position.locate.common.enums.DifferentiationDataType.SC_POWER_OFF;


/**
 * 滁州
 */
@Slf4j
@Service
public class PowerOffSysCheck implements DifferentiationService, SysCheck {
    @Resource
    private DifferentiationConfigService config;
    //缓存key
    private final static String POSITION_POWER_OFF_CACHE = "locate:powerOff:%s";
    @Resource
    private RedisTemplate<String, ReLocateCount> redisTemplate;


    @Override
    public DifferentiationDataType getType() {
        return SC_POWER_OFF;
    }



    /**
     * 是否需要重试
     */
    public Retry retry(LocateTimerTask.Task task,
                       PositionAddDTO position) {
        if (position == null) {
            return Retry.of(false);
        }
        DifferentiationService service = config.getService(this,getType(), task.getKey().getJgCode());
        if (service != null) {
            return ((PowerOffSysCheck) service).retry(task, position);
        }
        return Retry.of(false);
    }

    /**
     * 获取LocateCount
     * 没有则生成
     */
    protected ReLocateCount getLocateCount(String key,Integer maxRetry) {
        ReLocateCount count = redisTemplate.opsForValue().get(String.format(POSITION_POWER_OFF_CACHE, key));
        return ObjectUtil.defaultIfNull(count, new ReLocateCount(maxRetry));
    }

    /**
     * 保存
     * 30分钟的有效期
     */
    protected void saveLocateCount(String key, ReLocateCount count) {
        redisTemplate.opsForValue().set(
                String.format(POSITION_POWER_OFF_CACHE, key),
                count,
                30,
                TimeUnit.MINUTES
        );
    }

    /**
     * 删除缓存
     */
    protected void removeLocateCount(String key) {
        redisTemplate.delete(
                String.format(POSITION_POWER_OFF_CACHE, key)
        );
    }

}
